#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Name : __init__.py
# Author: ls_seraph@126.com
# Time  : 2021/3/6 22:46

from email import encoders
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import smtplib
from frame.common.util.config_util import config as yml


class EmailUtils():
    """
    初始化邮件发送
    """
    def __init__(self, smtp_body, smtp_file_path=None):
        mail = yml.get_option("email")
        self.smtp_server = mail["server"]  # 邮件服务器地址
        self.smtp_sender = mail["sender"]
        self.smtp_sender_password = mail["sender_password"]
        self.smtp_receiver = mail["receiver"]
        self.smtp_cc = mail["cc"]
        self.smtp_subject = mail["subject"]
        self.smtp_body = smtp_body
        self.smtp_file = smtp_file_path

    def mail_content(self):
        if self.smtp_file is not None:
            msg = MIMEMultipart()
            with open(self.smtp_file, 'rb') as f:
                mime = MIMEBase('zip', 'zip', filename=self.smtp_file.split('/')[-1])
                mime.add_header('Content-Disposition', 'attachment',
                                filename=('gb2312', '', self.smtp_file.split('/')[-1]))
                mime.add_header('Content-ID', '<0>')
                mime.add_header('X-Attachment-Id', '0')
                mime.set_payload(f.read())
                encoders.encode_base64(mime)
                msg.attach(mime)
            msg.attach(MIMEText(self.smtp_body, 'html', 'utf-8'))
            msg['from'] = self.smtp_sender
            msg['to'] = self.smtp_receiver
            msg['Cc'] = self.smtp_cc
            msg['subject'] = self.smtp_subject
            return msg
        else:
            msg = MIMEText(self.smtp_body, 'html', 'utf-8')
            msg['from'] = self.smtp_sender
            msg['to'] = self.smtp_receiver
            msg['Cc'] = self.smtp_cc
            msg['subject'] = self.smtp_subject
            return msg

    def send_mail(self, msg):
        try:
            smtp = smtplib.SMTP()
            smtp.connect(self.smtp_server)
            smtp.login(user=self.smtp_sender, password=self.smtp_sender_password)
        except Exception:
            smtp = smtplib.SMTP_SSL()
            smtp.login(user=self.smtp_sender, password=self.smtp_sender_password)
        try:
            smtp.sendmail(self.smtp_sender, self.smtp_receiver.split(',') + self.smtp_cc.split(','), msg.as_string())
        except Exception as e:
            print('发送失败')
        smtp.quit()
